<template>
  <div
    class="ring"
    :style="{
      height: height || '100%',
    }"
  >
    <div :id="cid" class="ring-dom" />
    <div class="actual-count f-col f-ai-c f-jc-c">
      <div>{{ value }}</div>
      <div v-if="title">{{ title }}</div>
    </div>
  </div>
</template>
<script>
export default {
  name: "Ring",
  props: {
    // 图表ID
    cid: {
      type: String,
      default: "ring",
    },
    // 数据  { value: 1, name: "", color: "#30c27c" },
    data: {
      type: Array,
      default: () => [],
    },
    // 显示值
    value: {
      type: [Number, String],
      default: "0%",
    },
    // 高度
    height: {
      type: String,
      default: "",
    },
    // 展示标题
    title: {
      type: String,
      default: "当天达成率",
    },
  },
  watch: {
    data: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.initPie();
        });
      },
    },
  },
  methods: {
    // 画饼图
    initPie() {
      let domid = document.getElementById(this.cid);
      if (domid?.hasAttribute("_echarts_instance_"))
        domid.removeAttribute("_echarts_instance_");
      let myChart = this.$echarts.init(domid);
      let name = `统计${new Date().getTime()}`;
      let option = {
        tooltip: { show: false },
        legend: { show: false },
        series: [
          {
            name,
            type: "pie",
            radius: ["55%", "70%"],
            color: this.data.map((i) => i.color),
            avoidLabelOverlap: false,
            selectedMode: "single", // 选中模式
            selectedOffset: 20, // 选中偏移
            clockwise: true, // 顺时针
            padAngle: 0.5,
            startAngle: 150,
            label: {
              show: true,
              color: "#fff",
            },
            labelLine: { show: false },
            emphasis: {
              scale: true,
              scaleSize: 14,
            },
            data: this.data,
          },
        ],
      };
      myChart.setOption(option, true, true);

      setTimeout(() => {
        let dataIndex = this.data.findIndex((i) => i.name);
        myChart.dispatchAction({
          type: "highlight",
          seriesName: name,
          dataIndex,
        });
      }, 10);

      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.ring {
  width: 100%;
  height: 100%;
  position: relative;
  &-dom {
    width: 100%;
    height: 100%;
  }
  .actual-count {
    position: absolute;
    left: 50%;
    top: 50%;
    width: 164px;
    height: 164px;
    border-radius: 50%;
    transform: translate(-50%, -50%);
    background: linear-gradient(180deg, #5589d8 0%, #2868ca 100%);
    color: #fff;
    > div:first-child {
      font-size: 24px;
    }
    > div:last-child {
      font-size: 20px;
    }
  }
}
</style>
